package com.baomidou.springwind.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.springwind.entity.*;
import com.baomidou.springwind.enums.FileTypeEnum;
import com.baomidou.springwind.excel.ExcelReader;
import com.baomidou.springwind.pojo.SiteSelection;
import com.baomidou.springwind.pojo.SiteSelectionBuilder;
import com.baomidou.springwind.service.*;
import com.baomidou.springwind.utils.SpringBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 文件管理相关操作
 * </p>
 *
 * @Author Jack
 * @Date 2016/4/15 15:03
 */
@Controller
@RequestMapping("/file")
public class FileController extends BaseController {

    @Autowired
    private FileService fileService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private ReceiveGoodsService receiveGoodsService;

    @Autowired
    private DeliveryGoodsService deliveryGoodsService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OthersService othersService;

    @Autowired
    private NetworkNodeService networkNodeService;

    @Permission("1001")
    @RequestMapping("/list/{fileType}")
    public String list(@PathVariable Integer fileType, Model model) {
//        FileTypeEnum fileTypeEnum = FileTypeEnum.valueOf(fileType);
//        model.addAttribute("fileType", fileTypeEnum.value);
        return pjaxPath("/file/list", model);
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/getFileList/{fileType}")
    public String getFileList(@PathVariable Integer fileType, Page<PubFile> page) {
        FileTypeEnum fileTypeEnum = FileTypeEnum.valueOf(fileType);
        EntityWrapper<PubFile> wrapper = new EntityWrapper<PubFile>();
        return jsonPage(fileService.selectPage(page, wrapper));
    }

    @Permission("1001")
    @RequestMapping("/uploadFile")
    public String uploadFile(Integer fileType, Model model) {
        FileTypeEnum typeEnum = FileTypeEnum.valueOf(fileType);
        model.addAttribute("fileType", typeEnum.value);
        return "/file/upload";
    }
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/listProject")
    public String centerList() {
        JSONObject ret = new JSONObject();
        EntityWrapper<Project> wrapper = new EntityWrapper<Project>();
        wrapper.eq("operator_id",getCurrentUserId());
        wrapper.in("state", Arrays.asList("1", "2"));
        wrapper.orderBy("create_time");
        List<Project> projects=projectService.selectList(wrapper);
        ret.put("prjList",projects);
        return callbackSuccess(ret);
    }


    @RequestMapping(value = "/upload", produces = "text/html;charset=utf-8")
    @ResponseBody
    @Permission("1001")
    public String uploadFlatness(@RequestParam("file") MultipartFile file ,@RequestParam Long prjId, HttpServletRequest request) {
        try {
            PubFile pubFile = new PubFile();
            pubFile.setSubject(request.getParameter("subject"));
            pubFile.setFileType(Integer.parseInt(request.getParameter("fileType")));
            pubFile.setPrjId(Long.valueOf(request.getParameter("prjId")));
            pubFile.setCreateTime(new Date());
            pubFile.setOperatorId(getCurrentUserId());
            fileService.insert(pubFile);
            FileTypeEnum typeEnum = FileTypeEnum.valueOf(pubFile.getFileType());
            ExcelReader reader = SpringBeanUtil.getBean(typeEnum.handler);
            String str0=reader.handleExcel(file.getInputStream(), prjId,file.getOriginalFilename());
            if(str0.length()>1){
                return callbackFail(str0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return callbackFail(e.getMessage());
        }
        return callbackSuccess(true);
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/downLoad")
    public byte[] expend1() throws IOException {
        String file_name=request.getParameter("file_name"); //要下载的文件名
        if(file_name==null){file_name="订单";}
        String file_name1=request.getParameter("file"); //要生成的文件名
        if(file_name1==null){file_name1="城市配送";}
        System.out.println("获取到的----"+file_name1);
        String realpath=request.getSession().getServletContext().getRealPath("/");//获取服务器的物理路径
        String temp1 = File.separator;//路径分隔符("\\")
        String filedownload_url=realpath+"WEB-INF"+temp1+"static"+temp1+"template"+temp1+file_name+".xls";//要提供下载的文件的物理路径＋文件名
        //创建文件
        try {
            // path是指欲下载的文件的路径。
            File file = new File(filedownload_url);
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(filedownload_url));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    new String((file_name1+ ".xls").getBytes(), "iso-8859-1"));
            OutputStream toClient = new BufferedOutputStream(
                    response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

}
